/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import fileio from '@ohos.fileio';
import worker from '@ohos.worker';

const parentPort = worker.parentPort;
parentPort.onmessage = function(e) {
    let dir = e.data.dir.toString();
    let targetFile = e.data.targetFile.toString();
    let fileList = e.data.fileList as Array<string>;
    fileList.sort();
    console.info("ok download fileWork fileList = " + JSON.stringify(fileList));
    const writeFd = fileio.openSync(dir + targetFile, 0o100 | 0o2, 0o666)
    let writeOffset: number = 0;
    //console.info("okdownload writeFd = " + writeFd)
    setTimeout(function(){
        for (var i = 0; i < fileList.length; i++) {
            let blockFile = fileList[i];
            let readFd = fileio.openSync(dir + blockFile, 0o2, 0o666);
            console.info("ok download 1111111 readFd = " + readFd)
            let buf = new ArrayBuffer(4096);
            let num: number = 0;
            let offset: number = 0;
            console.error("okdownload num = " + num + "; offset = " + offset + "; writeOffset = " + writeOffset)
            do {
                num = fileio.readSync(readFd, buf, { position: offset });
                fileio.writeSync(writeFd, buf, { position: writeOffset, length: num })
                offset = num + offset;
                writeOffset = num + writeOffset;
            } while (num != 0)
            fileio.unlinkSync(dir + blockFile);
        }
    }, 500)

}